package org.jetnuke.modules.blog.utils;

import org.apache.log4j.Logger;

import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

import net.jforum.entities.User;

import org.apache.xmlrpc.XmlRpcException;
import org.jetnuke.dao.BlogPostDAO;
import org.jetnuke.dao.DataAccessDriver;
import org.jetnuke.entities.BlogCategory;
import org.jetnuke.entities.BlogPost;

public class MovableTypeAPIHandler extends BaseAPIHandler {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger
			.getLogger(MovableTypeAPIHandler.class);

	protected static final String MEMBER_DATECREATED = "dateCreated";
	protected static final String MEMBER_USERID = "userid";
	protected static final String MEMBER_POSTID = "postid";
	protected static final String MEMBER_TITLE = "title";
	protected static final String MEMBER_CATEGORYID = "categoryId";
	protected static final String MEMBER_CATEGORYNAME = "categoryName";
	protected static final String MEMBER_ISPRIMARY = "isPrimary";

	protected static final String API_PREFIX = "mt";

	public String getName() {
		return API_PREFIX;
	}

	public Object supportedMethods() throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("supportedMethods() - start"); //$NON-NLS-1$
		}

		Vector result = new Vector();

		result.add("blogger.newPost");
		result.add("blogger.editPost");
		result.add("blogger.getPost");
		result.add("blogger.deletePost");
		result.add("blogger.getRecentPosts");
		result.add("blogger.getUsersBlogs");
		result.add("blogger.getUserInfo");
		result.add("metaWeblog.getUsersBlogs");
		result.add("metaWeblog.getCategories");
		result.add("metaWeblog.newPost");
		result.add("metaWeblog.editPost");
		result.add("metaWeblog.getPost");
		result.add("metaWeblog.deletePost");
		result.add("metaWeblog.getRecentPosts");
		result.add("metaWeblog.newMediaObject");
		result.add("mt.getRecentPostTitles");
		result.add("mt.getCategoryList");
		result.add("mt.getPostCategories");
		result.add("mt.supportedMethods");
		result.add("mt.supportedTextFilters");
		result.add("mt.getTrackbackPings");

		if (logger.isDebugEnabled()) {
			logger.debug("supportedMethods() - end"); //$NON-NLS-1$
		}
		return result;
	}

	public boolean setPostCategories(String postID, String username,
			String password, Vector categories) throws Exception {
		if (logger.isDebugEnabled()) {
			logger
					.debug("setPostCategories(String, String, String, Vector) - start"); //$NON-NLS-1$
		}

		throw new XmlRpcException(UNSUPPORTED_EXCEPTION,
				UNSUPPORTED_EXCEPTION_MSG);
	}

	public Object supportedTextFilters() throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("supportedTextFilters() - start"); //$NON-NLS-1$
		}

		Vector result = new Vector();

		if (logger.isDebugEnabled()) {
			logger.debug("supportedTextFilters() - end"); //$NON-NLS-1$
		}
		return result;
	}

	public Object getRecentPostTitles(String blogID, String username,
			String password, int numberOfPosts) throws Exception {
		if (logger.isDebugEnabled()) {
			logger
					.debug("getRecentPostTitles(String, String, String, int) - start"); //$NON-NLS-1$
		}

		User user = validate(username, password);

		try {
			Vector results = new Vector();
			BlogPostDAO bpm = DataAccessDriver.getInst().newBlogPostDAO();
			List entries = bpm.retrieveByUserOrdered(user.getId());
			Iterator it = entries.iterator();
			int counter = 0;
			while (it.hasNext()) {
				BlogPost blogPost = (BlogPost) it.next();
				Hashtable result = new Hashtable();
				result.put(MEMBER_DATECREATED, blogPost.getPOSTDATE());

				result.put(MEMBER_USERID, String.valueOf(blogPost.getAID()));

				result.put(MEMBER_POSTID, String.valueOf(blogPost.getID()));
				result.put(MEMBER_TITLE, blogPost.getPOSTTITLE());
				results.add(result);
				counter++;
				if (counter > numberOfPosts)
					break;
			}

			if (logger.isDebugEnabled()) {
				logger
						.debug("getRecentPostTitles(String, String, String, int) - end"); //$NON-NLS-1$
			}
			return results;
		} catch (Exception e) {
			logger.error("getRecentPostTitles(String, String, String, int)", e); //$NON-NLS-1$

			String msg = "ERROR in BlooggerAPIHander.getRecentPosts";

			throw new XmlRpcException(UNKNOWN_EXCEPTION, msg);
		}

	}

	public Object getCategoryList(String blogID, String username,
			String password) throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("getCategoryList(String, String, String) - start"); //$NON-NLS-1$
		}

		User user = validate(username, password);

		Vector result = null;
		try {

			List cats = DataAccessDriver.getInst().newBlogCategoryDAO()
					.selectByUser(user.getId());
			result = new Vector(cats.size());
			for (int i = 0; i < cats.size(); i++) {
				Hashtable catlist = new Hashtable(3);
				BlogCategory category = (BlogCategory) cats.get(i);

				String categoryId = String.valueOf(category.getID());

				String description = category.getNAME();

				catlist.put(MEMBER_CATEGORYID, categoryId);
				catlist.put(MEMBER_CATEGORYNAME, description);

				result.add(catlist);
			}
		} catch (Exception e) {
			logger.error("getCategoryList(String, String, String)", e); //$NON-NLS-1$

			String msg = "ERROR in BlooggerAPIHander.getRecentPosts";

			throw new XmlRpcException(UNKNOWN_EXCEPTION, msg);
		}

		if (logger.isDebugEnabled()) {
			logger.debug("getCategoryList(String, String, String) - end"); //$NON-NLS-1$
		}
		return result;

	}

	public Object getPostCategories(String postID, String username,
			String password) throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("getPostCategories(String, String, String) - start"); //$NON-NLS-1$
		}

		User user = validate(username, password);

		Vector result = new Vector();
		try {
			int index = postID.indexOf("id=");
			if (index > -1) {
				int id = Integer.parseInt(postID.substring(index + 3));
				BlogPost post = DataAccessDriver.getInst().newBlogPostDAO()
						.retrieveByPK(id);
				if (post.getAID() == user.getId()) {
					Hashtable categoryContent = new Hashtable(3);
					int postCatID = post.getPOSTCATEGORY();
					BlogCategory cat = DataAccessDriver.getInst()
							.newBlogCategoryDAO().retrieveByPK(postCatID);
					categoryContent.put(MEMBER_CATEGORYID, String
							.valueOf(postCatID));
					categoryContent.put(MEMBER_CATEGORYNAME, cat
							.getDESCRIPTION());
					categoryContent.put(MEMBER_ISPRIMARY, Boolean.TRUE);
					result.add(categoryContent);
				}
			}

		} catch (Exception e) {
			logger.error("getPostCategories(String, String, String)", e); //$NON-NLS-1$

			String msg = "ERROR in BlooggerAPIHander.getRecentPosts";

			throw new XmlRpcException(UNKNOWN_EXCEPTION, msg);
		}

		if (logger.isDebugEnabled()) {
			logger.debug("getPostCategories(String, String, String) - end"); //$NON-NLS-1$
		}
		return result;

	}

	public Object getTrackbackPings(String postID) throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("getTrackbackPings(String) - start"); //$NON-NLS-1$
		}

		Vector trackbackPings = new Vector();

		if (logger.isDebugEnabled()) {
			logger.debug("getTrackbackPings(String) - end"); //$NON-NLS-1$
		}
		return trackbackPings;
	}

	public boolean publishPost(String postID, String username, String password)
			throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("publishPost(String, String, String) - start"); //$NON-NLS-1$
		}

		throw new XmlRpcException(UNSUPPORTED_EXCEPTION,
				UNSUPPORTED_EXCEPTION_MSG);
	}
}
